package com.mc.read.common.config;

import com.mc.read.common.emun.ServiceCodeEnum;
import com.mc.read.common.exception.ServiceException;
import com.mc.read.vo.respose.BaseRespose;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @author liuhao
 * @date 2019/4/21 9:32
 * 定义一个全局异常处理类来处理异常。。AdviceControlle
 */
@RestController
@ControllerAdvice
@Slf4j
public class ExceptionHandler {
    @Autowired
    public HttpServletResponse httpServletResponse;
    /**
     * 全局异常
     * @param ex
     * @return
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    @CrossOrigin
    public BaseRespose authorizationException(Exception ex) {
        BaseRespose result = new BaseRespose();
        if (ex instanceof ServiceException) {
            result.setCode(((ServiceException) ex).getcode());
            result.setDisp(ex.getMessage());
            if(ObjectUtils.isEmpty(((ServiceException) ex).getRequest())){
                log.error("错误码:{}，错误说明:{}",((ServiceException) ex).getcode(),ex.getMessage());
            }else {
                log.error("错误码:{}，错误说明:{},参数为{}",((ServiceException) ex).getcode(),ex.getMessage(),((ServiceException) ex).getRequest());
            }
        }  else {
            result.setCode(ServiceCodeEnum.FAIL.getCode());
            result.setDisp(ServiceCodeEnum.FAIL.getDesc());
            log.error("错误码:{}，错误说明:{}",(ServiceCodeEnum.FAIL.getCode()),ex.getMessage());
        }
        result.setReturnString(" ");
        ex.printStackTrace();
        return  result;
    }
}
